<!-- 成品锁定 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :before-open="beforeOpen"
      :permission="permissionList"
      v-model="form"
      ref="crud"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button v-if="permission.finishedProductLock_unlock" type="danger" size="small" icon="el-icon-unlock" @click="handleBatchUnLock">批量解锁</el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button v-if="permission.finishedProductLock_unlock" icon="el-icon-unlock" size="small" type="text" @click="openUnLockDialog(row)" v-preventReClick>解锁</el-button>
        <el-button icon="el-icon-view" size="small" type="text" @click="$refs.crud.rowView(row)">详情</el-button>
      </template>
      <template slot="addWorkOrderNoForm">
        <p>待锁定的工单号：</p>
        <avue-crud :option="awitLockWorkOrderOption" :data="awitLockWorkOrderData" :class="dynamicClass">
          <template slot="menuLeft">
            <el-button v-if="awitLockWorkOrderOption.menu" type="primary" size="small" icon="el-icon-plus" @click="openWorkOrderModal">新增</el-button>
          </template>
          <template slot-scope="{ index }" slot="menu">
            <el-button icon="el-icon-delete" size="small" type="text" @click="workOrderDel(index)">删除</el-button>
          </template>
        </avue-crud>
      </template>
    </avue-crud>

    <!-- 解除锁定 -->
    <el-dialog custom-class="unlock-dialog" append-to-body :close-on-click-modal="false" title="解锁" :visible.sync="unlockDialog.show" width="50%" @close="closeUnlockDialog">
      <h3 class="custom-title" v-if="unLockType === 'single'"><i class="el-icon-vertical-bar mr10"></i>锁定信息</h3>
      <avue-form v-if="unLockType === 'single'" ref="unlockRef" v-model="unlockDialog.form" :option="unlockDialog.option"></avue-form>
      <h3 class="custom-title" v-if="unLockType === 'single' && unlockDialog.form.lockDimension === 'WORKORDER'"><i class="el-icon-vertical-bar mr10"></i>已锁定工单号</h3>
      <avue-crud v-if="unLockType === 'single' && unlockDialog.form.lockDimension === 'WORKORDER'" :option="unlockDialog.tableOption" :data="unlockDialog.table"></avue-crud>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>解除锁定</h3>
      <avue-form ref="unlockRemarkRef" v-model="unlockDialog.remarkForm" :option="unlockDialog.remarkOption"></avue-form>
      <h3 class="custom-title" v-if="unLockType != 'single'"><i class="el-icon-vertical-bar mr10"></i>选中锁定信息</h3>
      <avue-crud v-if="unLockType != 'single'" :option="unlockDialog.selectProductOption" :data="unlockDialog.selectProductData">
        <template slot="lockDimensionDetail" slot-scope="scope">
          <span v-if="scope.row.lockDimensionDetail === 'FINISHED'">产品</span>
          <el-tooltip v-if="scope.row.lockDimensionDetail != 'FINISHED'" class="item" effect="dark" :content="scope.row.lockDimensionDetail" placement="top-start">
            <span>{{ scope.row.lockDimensionDetail }}</span>
          </el-tooltip>
        </template>
        <template slot-scope="{ index }" slot="menu">
          <el-button icon="el-icon-delete" size="small" type="text" @click="productDel(index)">删除</el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="unlockDialog.show = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button type="primary" size="small" @click="handleunLockSubmit" v-preventReClick> <i class="el-icon-circle-plus-outline"></i><span>解 锁</span> </el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, partLock, getDetail, unLock, batchUnlock } from '@/api/quality/finishedProductLock';
import { mapGetters } from 'vuex';
export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      unLockType: 'single', // 解锁类型:单个解锁还是批量解锁
      search: {},
      option: {
        height: 'calc(100vh - 420px)',
        calcHeight: 30,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        selection: true,
        dialogClickModal: false,
        addBtn: true,
        addBtnText: '新增锁定',
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        indexLabel: '序号',
        dialogWidth: '50%',
        menuWidth: 150,
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            searchOrder: 2,
            width: 150,
            display: false
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            width: 150,
            display: false
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            search: true,
            searchOrder: 3,
            display: false
          },
          {
            label: '锁定维度',
            prop: 'lockDimension',
            type: 'select',
            dicData: [
              { label: '产品', value: 'FINISHED' },
              { label: '工单', value: 'WORKORDER' }
            ],
            display: false
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 4,
            hide: true,
            display: false
          },
          {
            label: '锁定原因',
            prop: 'lockReason',
            display: false
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            display: false,
            html: true,
            formatter: (val) => {
              switch (val.status) {
                case 2:
                  return `<span class="stateWords-success">已解锁</span>`;
                case 1:
                  return `<span class="stateWords-danger">已锁定</span>`;
                default:
                  break;
              }
            }
          },
          {
            label: '操作人',
            prop: 'lockByName',
            display: false
          },
          {
            label: '操作时间',
            prop: 'lockTime',
            searchSpan: 8,
            searchType: 'datetimerange',
            search: true,
            searchOrder: 1,
            width: 130,
            display: false,
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
          },
          {
            label: '已锁定时间',
            prop: 'lockDuration',
            display: false
          }
        ],
        group: [
          {
            label: '产品信息',
            prop: 'partInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '产品编码',
                prop: 'productPartNo',
                type: 'search',
                disabled: true,
                appendClick: () => {
                  this.openPartModal();
                },
                rules: [
                  {
                    required: true,
                    message: '请选择产品编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '产品名称',
                prop: 'productPartName',
                disabled: true
              },
              {
                label: '产品型号',
                prop: 'productPartModel',
                disabled: true
              }
            ]
          },
          {
            label: '锁定维度',
            prop: 'lockDimension',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '',
                prop: 'lockDimension',
                labelWidth: 10,
                type: 'radio',
                dicData: [
                  { label: '产品', value: 'FINISHED' },
                  { label: '工单号', value: 'WORKORDER' }
                ],
                value: 'FINISHED',
                change: (val) => {
                  this.changeLockDimension(val);
                }
              },
              {
                label: '',
                prop: 'addWorkOrderNo',
                span: 24,
                labelWidth: 10,
                formslot: true,
                display: false
              }
            ]
          },
          {
            column: [
              {
                label: '锁定原因',
                prop: 'lockReason',
                type: 'textarea',
                row: true,
                span: 24,
                maxRows: 3,
                minRows: 3,
                rules: [
                  {
                    required: true,
                    message: '请输入锁定原因',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          }
        ]
      },
      awitLockWorkOrderOption: {
        height: '200px',
        calcHeight: 30,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        tip: false,
        indexLabel: '序号',
        menu: true,
        menuWidth: 100,
        column: [
          { label: '工单号', prop: 'workOrderNo' },
          { label: '生产批次', prop: 'lotNo' },
          {
            label: '工单状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          }
        ]
      },
      awitLockWorkOrderData: [],
      unlockDialog: {
        show: false,
        form: {},
        option: {
          submitBtn: false,
          emptyBtn: false,
          detail: true,
          column: [
            { label: '产品编码', prop: 'productPartNo' },
            { label: '产品名称', prop: 'productPartName' },
            { label: '产品型号', prop: 'productPartModel' },
            {
              label: '锁定维度',
              prop: 'lockDimension',
              type: 'select',
              dicData: [
                { label: '产品', value: 'FINISHED' },
                { label: '工单', value: 'WORKORDER' }
              ]
            },
            { label: '锁定原因', prop: 'lockReason', type: 'textarea', span: 24, maxRows: 3, minRows: 3 }
          ]
        },
        table: [],
        tableOption: {
          height: '200px',
          calcHeight: 30,
          border: true,
          index: true,
          selection: false,
          addBtn: false,
          viewBtn: false,
          editBtn: false,
          delBtn: false,
          refreshBtn: false,
          columnBtn: false,
          tip: false,
          indexLabel: '序号',
          menu: false,
          column: [
            { label: '工单号', prop: 'workOrderNo' },
            { label: '生产批次', prop: 'lotNo' },
            {
              label: '工单状态',
              prop: 'status',
              type: 'select',
              dicData: [
                {
                  label: '待排程',
                  value: 1
                },
                {
                  label: '待生产',
                  value: 2
                },
                {
                  label: '生产中',
                  value: 3
                },
                {
                  label: '完工',
                  value: 4
                },
                {
                  label: '锁定',
                  value: 5
                },
                {
                  label: '强制完工',
                  value: 6
                }
              ]
            }
          ]
        },
        remarkForm: {},
        remarkOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '解锁说明',
              prop: 'unlockReason',
              type: 'textarea',
              span: 24,
              maxRows: 3,
              minRows: 3,
              rules: [
                {
                  required: true,
                  message: '请输入解锁说明',
                  trigger: 'submit'
                }
              ]
            }
          ]
        },
        selectProductData: [],
        selectProductOption: {
          height: '200px',
          calcHeight: 30,
          border: true,
          index: true,
          selection: false,
          addBtn: false,
          viewBtn: false,
          editBtn: false,
          delBtn: false,
          refreshBtn: false,
          columnBtn: false,
          tip: false,
          indexLabel: '序号',
          menu: true,
          menuWidth: 100,
          column: [
            { label: '产品编码', prop: 'productPartNo' },
            { label: '产品名称', prop: 'productPartName' },
            { label: '产品型号', prop: 'productPartModel' },
            { label: '锁定维度', prop: 'lockDimensionDetail' },
            { label: '锁定原因', prop: 'lockReason' }
          ]
        }
      },
      loading: true,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      form: {},
      query: {},
      selectionList: [],
      modalName: '',
      tableOption: {},
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.finishedProductLock_add, false)
      };
    },
    dynamicClass() {
      // 根据你的逻辑返回不同的 class
      return !this.awitLockWorkOrderOption.menu ? 'hideMenu' : '';
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    searchChange(params, done) {
      if (params.lockTime && params.lockTime.length > 0) {
        params.startTime = params.lockTime[0];
        params.endTime = params.lockTime[1];
        delete params.lockTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 打开物料选择模态框
     */
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'partModal';
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page?statusStr=1,4&partTypeStr=FINISHED,SEMIFINISHED',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            minWidth: 150
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true,
            width: 150
          },
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '物料型号',
            prop: 'partModel',
            width: 150
          },
          {
            label: '描述',
            prop: 'description',
            width: 150
          },
          {
            label: '版本',
            prop: 'revision',
            width: 150
          }
        ]
      };
    },
    /**
     * 锁定维度改变
     * @param val
     */
    changeLockDimension(val) {
      let addWorkOrderNo = this.findObject(this.option.group[1].column, 'addWorkOrderNo');
      if (val.value === 'WORKORDER') {
        addWorkOrderNo.display = true;
      } else {
        addWorkOrderNo.display = false;
      }
    },
    /**
     * 打开工单选择模态框
     */
    openWorkOrderModal() {
      if (!this.form.productPartNo) {
        this.$message({
          type: 'warning',
          message: '请先选择产品编码！'
        });
        return;
      }
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'workOrderModal';
      this.tableOption = {
        modalTitle: '选择工单信息',
        url: `/api/mes-product/work-order/page?productPartId=${this.form.productPartId}&workOrderStatus=1,2,3,4,6`,
        isPage: true,
        index: false,
        rowSelectionType: 'multiple',
        searchMenuSpan: 6,
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchType: 'input'
          },
          {
            label: '生产工单',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'type',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            searchType: 'input'
          },
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartTime'
          },
          {
            label: '计划结束时间',
            prop: 'planEndTime'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            search: true,
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          }
        ]
      };
    },
    /**
     * 删除待锁定工单
     * @param index
     */
    workOrderDel(index) {
      this.awitLockWorkOrderData.splice(index, 1);
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partModal':
          this.form.productPartId = this._get(rowData, 'id', '');
          this.form.productPartNo = this._get(rowData, 'partNo', '');
          this.form.productPartName = this._get(rowData, 'name', '');
          this.form.productPartModel = this._get(rowData, 'partModel', '');
          break;
        case 'workOrderModal':
          this._forEach(rowData, (item) => {
            let obj = this._find(this.awitLockWorkOrderData, { workOrderNo: item.workOrderNo });
            if (!obj) {
              this.awitLockWorkOrderData.push({
                workOrderNo: item.workOrderNo,
                lotNo: item.lotNo,
                status: item.status
              });
            }
          });
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    rowSave(row, done, loading) {
      if (row.lockDimension === 'WORKORDER' && this.awitLockWorkOrderData.length === 0) {
        this.$message({
          type: 'warning',
          message: '请添加至少一条待锁定的工单！'
        });
        loading();
        return;
      }
      let params = {
        productPartId: row.productPartId,
        productPartNo: row.productPartNo,
        productPartName: row.productPartName,
        productPartModel: row.productPartModel,
        lockDimension: row.lockDimension,
        lockReason: row.lockReason
      };
      if (params.lockDimension === 'FINISHED') {
        params.lockDimensionDetail = 'FINISHED';
      } else {
        let workOrderList = this.awitLockWorkOrderData.map((item) => item.workOrderNo);
        params.lockDimensionDetail = workOrderList.join(',');
      }
      partLock(params).then(
        (res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    handleBatchUnLock() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.unLockType = 'batch';
      this.unlockDialog.show = true;
      this.unlockDialog.selectProductData = this.selectionList;
    },
    productDel(index) {
      this.unlockDialog.selectProductData.splice(index, 1);
    },
    openUnLockDialog(row) {
      this.unLockType = 'single';
      this.unlockDialog.show = true;
      getDetail(row.id).then((res) => {
        this.unlockDialog.form = this._get(res, 'data.data', {});
        if (this.unlockDialog.form.lockDimension === 'WORKORDER') {
          this.unlockDialog.table = this._get(res, 'data.data.workOrderVOList', []);
        }
      });
    },
    closeUnlockDialog() {
      if (this.unLockType === 'single') {
        this.$refs.unlockRef.resetFields();
        this.unlockDialog.form = {};
        if (this.unlockDialog.form.lockDimension === 'WORKORDER') {
          this.unlockDialog.table = [];
        }
      } else {
        this.unlockDialog.selectProductData = [];
      }
      this.$refs.unlockRemarkRef.resetFields();
      this.unlockDialog.remarkForm = {};
    },
    beforeOpen(done, type) {
      if (['view'].includes(type)) {
        this.awitLockWorkOrderOption.menu = false;
        getDetail(this.form.id).then((res) => {
          this.form = this._get(res, 'data.data', {});
          if (this.form.lockDimension === 'WORKORDER') {
            this.awitLockWorkOrderData = this._get(res, 'data.data.workOrderVOList', []);
          }
        });
      }
      if (['add'].includes(type)) {
        this.awitLockWorkOrderOption.menu = true;
      }
      this.awitLockWorkOrderData = [];
      done();
    },
    handleunLockSubmit() {
      this.$refs.unlockRemarkRef.validate((valid, done, msg) => {
        if (valid) {
          let params = {};
          if (this.unLockType === 'single') {
            params = {
              idList: [this.unlockDialog.form.id],
              unlockReason: this.unlockDialog.remarkForm.unlockReason
            };
          } else {
            if (this.unlockDialog.selectProductData.length === 0) {
              this.$message.warning('请选择至少一条锁定信息');
              done();
              return;
            }
            params = {
              idList: this.unlockDialog.selectProductData.map((item) => item.id),
              unlockReason: this.unlockDialog.remarkForm.unlockReason
            };
          }
          unLock(params).then((res) => {
            this.unlockDialog.show = false;
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: res.data.msg
            });
          });
          done();
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-table {
  margin-bottom: 10px;
}
.tdStyle {
  background: #fafafa;
  font-weight: 700;
  color: #909399;
  text-align: right;
  width: auto;
  padding-right: 20px;
  white-space: nowrap;
}
td {
  padding: 5px;
  border: 1px solid #ebeef5;
}
.detail-title {
  font-weight: bold;
  font-size: 14px;
  margin: 10px 0;
}
::v-deep .unlock-dialog {
  .el-dialog__body {
    padding-top: 0;
    .avue-crud__menu {
      display: none;
    }
  }
}
.hideMenu {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
.custom-title {
  font-size: 16px;
  font-weight: bold;
  .mr10 {
    margin-right: 10px;
  }
}
</style>
